//
//  LiveRoomViewController.swift
//  live
//
//  Created by melvyn on 2018/8/9.
//  Copyright © 2018年 NEET. All rights reserved.
//

import UIKit
import SnapKit
import Link

class LiveStreamRoomViewController: UIViewController {
    
    @IBOutlet weak var glView: UIView!
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var presentButton: UIButton!
    @IBOutlet weak var avatar: UIImageView!
    @IBOutlet weak var uploadTextLabel: UILabel!
    @IBOutlet weak var upLvTextLabel: UILabel!
    @IBOutlet weak var rankTextLabel: UILabel!
    @IBOutlet weak var hotsTextLabel: UILabel!
    @IBOutlet weak var fansTextLabel: UILabel!
    @IBOutlet weak var subscribeButton: UIButton!
    
    @IBOutlet weak var editorBottomLayout: NSLayoutConstraint!
    
    var viewModel: LiveStreamRoomViewModel!
    
    override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
        return .landscapeRight
    }
    
    override var preferredStatusBarStyle: UIStatusBarStyle {
        return .lightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        glView.addSubview(ijkView)
        ijkView.snp.makeConstraints { (make) in
            make.edges.equalTo(UIEdgeInsets(top: 44, left: 0, bottom: 0, right: 0))
        }
        
        viewDidAppear
            .bind(to: ijkplayer.rx.prepare)
            .disposed(by: disposeBag)
        
        registerForLocalNotification()
        
        viewModel.avatar
            .bind(to: avatar.rx.image)
            .disposed(by: disposeBag)
        
        viewModel.nickname
            .drive(uploadTextLabel.rx.text)
            .disposed(by: disposeBag)
        
        viewModel.level
            .drive(upLvTextLabel.rx.text)
            .disposed(by: disposeBag)
        
        textField.rx.text
            .bind(to: viewModel.comment)
            .disposed(by: disposeBag)
        
        textField.rx.controlEvent(.editingDidEndOnExit)
            .filter({ _ in !AppManager.default.API.base.isLoggedIn })
            .flatMapLatest({ _ in
                Link.shared.rx.performBasicAuthLogin()
            })
            .subscribe(onNext: {
                guard $0.isSuccess else {
                    let window = UIApplication.shared.keyWindow!
                    let hud = MBProgressHUD.showAdded(to: window, animated: true)
                    hud.label.text = $0.error?.localizedDescription
                    hud.hide(animated: true, afterDelay: 0.5)
                    return
                }
            })
            .disposed(by: disposeBag)
        
        textField.rx.controlEvent(.editingDidEndOnExit)
            .filter({ _ in AppManager.default.API.base.isLoggedIn })
            .bind(to: viewModel.compose)
            .disposed(by: disposeBag)
    }
    
    private func registerForLocalNotification() {
        NotificationCenter.default.rx.notification(UIResponder.keyboardWillChangeFrameNotification)
            .map { note in
                (
                    note.userInfo![UIResponder.keyboardFrameBeginUserInfoKey] as! CGRect,
                    note.userInfo![UIResponder.keyboardFrameEndUserInfoKey] as! CGRect,
                    note.userInfo![UIResponder.keyboardAnimationDurationUserInfoKey] as! TimeInterval
                )
            }
            .subscribe(onNext: { (beginFrame, endFrame, duration) in
                
                UIView.animate(withDuration: duration * 1.5, animations: { [weak self] in
                    let isEditing = beginFrame.origin.y > endFrame.origin.y
                    
                    self?.editorBottomLayout.constant = isEditing ? (self?.view.bounds.height ?? 0) - 34 - endFrame.origin.y : 0
                    self?.view.layoutIfNeeded()
                    }, completion: nil)
            })
            .disposed(by: disposeBag)
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        guard let destination = segue.destination as? DanmakuViewController else {
            super.prepare(for: segue, sender: sender)
            return
        }
        destination.alignment = .top
        destination.viewModel = viewModel.danmakuListViewModel
    }
}

extension LiveStreamRoomViewController {
    private var ijkView: UIView {
        return viewModel.ijkplayer.view
    }
    
    private var ijkplayer: IJKFFMoviePlayerController {
        return viewModel.ijkplayer
    }
}
